#甘肃数据，需要把地市信息加入到数据的头部
#具体的步骤是第一步解压到临时文件，第二步读取excel，读取信息，写入到新的out文件, 最后压缩文件
from zipfile import ZipFile
import zipfile
import xlrd
import os
import easygui

#把地市的号段做成字典
dict0={
    "临夏":"+8613800930500",
    "白银":"+8613800943500",
    "兰州":"+8613800931500",
    "定西":"+8613800932500",
    "平凉":"+8613800933500",
    "庆阳":"+8613800934500",
    "武威":"+8613800935500",
    "张掖":"+8613800936500",
    "酒泉":"+8613800937500",
    "天水":"+8613800938500",
    "陇南":"+8613800939500",
    "甘南":"+8613800941500",
    "金昌":"+8613800935500",
    "嘉峪关":"+8613800937500",

    }




#添加文件到压缩zip包
def addzip(filename):
    f = zipfile.ZipFile(filename,'w',zipfile.ZIP_DEFLATED)
    for i in files:
        file = i.split('/')[-1]
        f.write(i, file) #这个file是文件名，意思是直接把文件添加到zip没有文件夹层级， f.write(i)这种写法，则会出现上面路径的层级
    f.close()

#解压zip文件
def unzip_file(filename):
    # specifying the zip file name
    #file_name = "a.zip"

      
    # opening the zip file in READ mode
    with ZipFile(filename, 'r') as zip:
        # printing all the contents of the zip file
        zip.printdir()
      
        # extracting all the files
        print('Extracting all the files now...')
        zip.extractall(path='tmp')
        print('Done!')

#读取excel并写入新out文件
def action(xls,out):
    book = xlrd.open_workbook(xls)
    #print("The number of worksheets is {0}".format(book.nsheets))
    #print("Worksheet name(s): {0}".format(book.sheet_names()))
    sh = book.sheet_by_name('订单摘要')
    city=sh.cell_value(rowx=11, colx=0)
    print(city)
    code=dict0[sh.cell_value(rowx=11, colx=0)]
    with open(out,'r') as file:
        #x=file.read()
        x0=file.readlines()
    if len(x0[0])<30:
        pass
    else:
        with open(out,'r') as file:
            x=file.read()
        with open(out+"_processed",'w') as file:
            file.write(city+' '+code+'\n'+x)

#弹出的选zip文件的框
zipfile0=easygui.fileopenbox(multiple=True)
print(zipfile0)
#每个文件都要解压，做操作，再重新压缩
for file in zipfile0:
    unzip_file(file)
    path0='./tmp/'
    xls=os.listdir(path0)[0]
    out=os.listdir(path0)[1]
    print(path0+xls,path0+out)

    action(path0+xls,path0+out)           
    files=[path0+xls,path0+out,path0+out+"_processed"]
    addzip(file)
    os.remove(path0+xls)
    os.remove(path0+out+"_processed")
    os.remove(path0+out)
    os.rmdir(path0)
print("end")
